package com.example.tanhuanapp.server.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.tanhuanapp.server.ShortNoteServer;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author IT空门_门主
 * @date 2024/1/8
 * 短信
 */
@Slf4j
@Service
public class ShortNoteServerImpl implements ShortNoteServer {
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.sms.signName}")
    private String signName;
    @Value("${aliyun.sms.templateCode}")
    private String  templateCode;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Map<String, Object> sendCheckCode(String phone) {
        //通过HashMap来存在
        Map<String, Object> result = new HashMap<>(2);
        //redis头
        String redisKey = "CHECK_CODE:" + phone;
        /**
         * 如果redis中有就进行查询-返回
         */
        String redisCode= stringRedisTemplate.opsForValue().get(redisKey);
        log.info("redis存储的验证码:{}",redisCode);
        if (StringUtils.isNotBlank(redisCode)){
            result.put("code",1);
            result.put("msg","上次发送的验证码还未失效");
            return result;
        }

        //随机生成验证码(4位)
        Map<String, String> codeMap =new HashMap<>();
        codeMap.put("code",RandomUtil.randomNumbers(6));
        //发送验证码
        try {
            String sms = sms(phone,codeMap);
            log.info("验证码:{}",sms);
            log.info("电话:{}",phone);
            if(sms.equals("OK")){
                //保存到redis,2分种后失效
                stringRedisTemplate.opsForValue().set(redisKey,codeMap.get("code"),1200, TimeUnit.SECONDS);
                log.info("发送成功");
                result.put("code",3);
                result.put("msg","OK");
                return result;
            }else {
                result.put("code",2);
                result.put("msg","发送短信验证码失败");
                return result;
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 短信验证
     * @param phone
     * @param
     * @return
     */
    public String sms(String phone,Map<String, String> codeMap ) throws Exception {
        //-------------------------阿里云-短信验证代码------------------

        Client client =client(accessKeyId,accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phone)
                .setTemplateParam(JSONUtil.toJsonStr(codeMap));//4为的随机验证码
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info("短信验证结果:{}"+resp.getStatusCode());
            log.info("短信验证结果:{}"+resp.getBody().getMessage());
            return resp.getBody().getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 请求方法
     * @param setAccessKeyId
     * @param setAccessKeySecret
     * @return
     * @throws Exception
     */
    private Client client(String setAccessKeyId, String setAccessKeySecret) throws Exception {
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(setAccessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(setAccessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }



}
